package com.lanou3g.k12.service.impl;

import com.google.gson.Gson;
import com.lanou3g.k12.service.ImageHandlerService;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class QiNiuYunImageHandlerServiceImpl implements ImageHandlerService {
    @Override
    public String getimageSrc(InputStream inputStream) throws IOException {

        byte[] bytes = IOUtils.toByteArray(inputStream);
        Configuration configuration = new Configuration(Zone.zone1());
        UploadManager uploadManager = new UploadManager(configuration);
        Auth auth = Auth.create("TTwZWZwppYXb4F6tfVN_oa9uQJx8-G9aXTc2l165","fZTLRW68KNcC1qDsljK36EflLq80dIt4dZTUfo37");
        String bucket = "k12";
        String key = UUID.randomUUID().toString().replaceAll("-","")+".jpg";
        String upToken = auth.uploadToken(bucket);
        Response response = uploadManager.put(bytes, key, upToken);
        DefaultPutRet defaultPutRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        String imageSrc = "http://pry1nv38x.bkt.clouddn.com/" + defaultPutRet.key;

        return imageSrc;
    }

    @Override
    public void deletePicture(String src) {

        Auth auth = Auth.create("TTwZWZwppYXb4F6tfVN_oa9uQJx8-G9aXTc2l165", "fZTLRW68KNcC1qDsljK36EflLq80dIt4dZTUfo37");
        Configuration config = new Configuration(Zone.zone1());
        BucketManager bucketManager = new BucketManager(auth, config);
        String bucket = "k12";
        String key = src.substring(src.indexOf("com/")+4);
        try {
            Response delete = bucketManager.delete(bucket,key);
            delete.close();
        } catch (QiniuException e) {
            e.printStackTrace();
        }

    }

}
